package com.ltu.util.common;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;

import com.ltu.domain.mp_entity.UserEntity;
import com.ltu.util.datetime.DateUtils;

import cn.hutool.core.util.RandomUtil;



public class StrUtils {
	/**
	 * 判断字符串是否为空或者空串
	 * @param str
	 */
	public static boolean isTrimNull(String str){
		if(null == str || str.trim().length() == 0)
			return true;
		return false;
	}
	/**
	 * 根据出生日期计算年龄
	 * @param birthDay
	 * @return
	 */
	public static int getAge(Date birthDay) {
		Calendar cal = Calendar.getInstance();
		if (cal.before(birthDay)) { // 出生日期晚于当前时间，无法计算
			throw new IllegalArgumentException("The birthDay is before Now.It's unbelievable!");
		}
		int yearNow = cal.get(Calendar.YEAR); // 当前年份
		int monthNow = cal.get(Calendar.MONTH); // 当前月份
		int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH); // 当前日期
		cal.setTime(birthDay);
		int yearBirth = cal.get(Calendar.YEAR);
		int monthBirth = cal.get(Calendar.MONTH);
		int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
		int age = yearNow - yearBirth; // 计算整岁数
		if (monthNow <= monthBirth) {
			if (monthNow == monthBirth) {
				if (dayOfMonthNow < dayOfMonthBirth)
					age--;// 当前日期在生日之前，年龄减一
			} else {
				age--;// 当前月份在生日之前，年龄减一

			}
		}
		return age;
	}
	
	/**
	 * 判断数值是否有效，不为空，大于0
	 *
	 */
	public static Boolean isVaileNum(Number number){

		if(null == number)
			return false;
		if(number instanceof Double){
			Double value = (Double) number;
			if(value > 0)
				return true;
		}else if(number instanceof Float){
			Float value = (Float) number;
			if(value > 0)
				return true;
		}else if(number instanceof Integer){
			Integer value = (Integer) number;
			if(value > 0)
				return true;
		}else if(number instanceof Long){
			Long value = (Long) number;
			if(value > 0)
				return true;
		}else{
			if(number.intValue() > 0)
				return true;
		}
		return false;
	}
	
	/**
	 * 返回对象的int类型的值
	 * valueObj 对象
	 */
	public static Integer getIntValue(Object valueObj){
		Integer value = null;
		if(valueObj instanceof Integer){
			value = (Integer) valueObj;
		}else if(valueObj instanceof String){
			try {
				Double dValue = Double.valueOf((String)valueObj);
				value = dValue.intValue();
			} catch (Exception e) {
				value = null;
			}
		}else if(valueObj instanceof Double){
			Double dValue = (Double) valueObj;
			value = dValue.intValue();
		}else if(valueObj instanceof Float){
			Float fValue = (Float) valueObj;
			value = fValue.intValue();
		}else if(valueObj instanceof Long){
			Long lValue = (Long) valueObj;
			lValue.intValue();
		}
		return value;
	}
	/**
	 * 返回容器key的Int值
	 * @param map 容器
	 * @param key key
	 * @param infos
	 * @return
	 */
	public static Integer getIntValue(Map map, String key){
		if(null == map || map.size() == 0 || !map.containsKey(key) 
				|| key == null || isTrimNull(key)){
			return null;
		}
		Object valueObj = map.get(key);
		Integer value = getIntValue(valueObj);
		return value;
	}
	
	

	
	 // 获取2个值之间的随机数
    public static long randomnum(int smin, int smax)
    {
                 int range = smax - smin;
                double rand = Math.random();
                return (smin + Math.round(rand * range));
    }
    /**
     * 
     * @time:2018年9月26日
     * @author:若尘
     * @Description:获取指定位数的随机字符串
     * @param:@param len
     * @param:@return
     * @return:String
     */
    public  static  String  getRandmStr(Integer  len){
    	StringBuilder  sb=new StringBuilder();
    	Random  ran=new Random();
    	for(int i=0; i<len;i++){
    		boolean b =ran.nextBoolean();
    		if(b){ //下一位类型为字符
    			int  code=ran.nextBoolean()?65:97;
    			char c=(char)(int)(Math.random()*26+code);
    			sb.append(c);
    		}else{//下一位类型为数字
    			sb.append(String.valueOf((ran.nextInt(10))));
    		}
    	}
    	return  sb.toString();
    }
    
 
    public static  int[]   strToArry(String  str){
    	String[] strArry = str.split(",");
      int[]	array = new int[strArry.length];
    	for (int i = 0; i < strArry.length; i++) {
    		if(StringUtils.isNotBlank(strArry[i] ))
    			array[i] = Integer.parseInt(strArry[i]);
    	}
    	return  array;
    }
    public static  Set<Byte>   strToSetByte(String  str){
    	String[] strArry = str.split(",");
    	Set<Byte>	array = new HashSet<Byte>(strArry.length);  
    	for (int i = 0; i < strArry.length; i++) {
    		if(StringUtils.isNotBlank(strArry[i] ))
    			array.add( Byte.parseByte(strArry[i]));
    	}
    	return  array;
    }
    public static  Set<Integer>   strToSetInt(String  str){
    	String[] strArry = str.split(",");
    	Set<Integer>	array = new HashSet<Integer>(strArry.length);  
    	for (int i = 0; i < strArry.length; i++) { 
    		if(StringUtils.isNotBlank(strArry[i] ))
    			array.add( Integer.parseInt(strArry[i]));
    	}
    	return  array;
    }
    
    public static  Set<Integer>   arrToSetInt(String[]  str){
    	Set<Integer>	array = new HashSet<Integer>(str.length);  
    	for (int i = 0; i < str.length; i++) {    		
    		array.add( Integer.parseInt(str[i]));
    	}
    	return  array;
    }
    
    public static String arrayToStr(List list, char separator) {    
    	return StringUtils.join(list.toArray(),separator);    
    }

	/**
	 * 将emoji表情替换成*
	 *
	 * @param source
	 * @return 过滤后的字符串
	 */
	public static String filterEmoji(String source) {
		if(!StrUtils.isTrimNull(source)){
			return source.replaceAll("[\\ud800\\udc00-\\udbff\\udfff\\ud800-\\udfff]", "");
		}else{
			return source;
		}
	}
	/**
	 * @author 若尘
	 * @Description 返回十六进制字符串
	 * @param digest
	 * @return
	 * String
	 */
	public static String  byteToString(byte[] digest) {
		StringBuffer hexstr = new StringBuffer();
		String shaHex = "";
		for (int i = 0; i < digest.length; i++) {
			shaHex = Integer.toHexString(digest[i] & 0xFF);
			if (shaHex.length() < 2) {
				hexstr.append(0);
			}
			hexstr.append(shaHex);
		}
		return hexstr.toString();
	}
	 private static int parse(char c) {
	        if (c >= 'a') return (c - 'a' + 10) & 0x0f;
	        if (c >= 'A') return (c - 'A' + 10) & 0x0f;
	        return (c - '0') & 0x0f;
	    }
		
	
    // 从十六进制字符串到字节数组转换 
    public static byte[] HexString2Bytes(String hexstr) {
        byte[] b = new byte[hexstr.length() / 2];
        int j = 0;
        for (int i = 0; i < b.length; i++) {
            char c0 = hexstr.charAt(j++);
            char c1 = hexstr.charAt(j++);
            b[i] = (byte) ((parse(c0) << 4) | parse(c1));
        }
        return b;
    }
    
	
	//是否是数字类型，包含小数
    public static boolean isNumeric(String str) {
        // 该正则表达式可以匹配所有的数字 包括负数
        Pattern pattern = Pattern.compile("-?[0-9]+\\.?[0-9]*");//小数合法
//        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");//小数不合法
        String bigStr;
        try {
            bigStr = new BigDecimal(str).toString();
        } catch (Exception e) {
            return false;//异常 说明包含非数字。
        }

        Matcher isNum = pattern.matcher(bigStr); // matcher是全匹配
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }
    //过滤特殊字符串
    public static String StringFilter(String str) { 
    	// 只允许字母和数字 // String regEx ="[^a-zA-Z0-9]"; 
    	// 清除掉所有特殊字符 
    	String regEx="[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]"; 
    	Pattern p = Pattern.compile(regEx); 
    	Matcher m = p.matcher(str);
    	return m.replaceAll("").trim();
    }
   
    //判断字符是否为整数
    public static boolean isInteger(String str) {  
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");  
        return pattern.matcher(str).matches();  
  }
 // 判断一个字符串是否含有数字
    public static boolean HasDigit(String content) {
        boolean flag = false;
        Pattern p = Pattern.compile("^[-\\+]?[\\d]*$");
        Matcher m = p.matcher(content);
        if (m.matches()) {
            flag = true;
        }
        return flag;
    }
   
    public static List<String> getStringList(String ids){
		List<String> arrayList = new ArrayList<String>();
		if (!ids.isEmpty()) {
			String[] idArry = ids.split(",");

			for (int i = 0; i < idArry.length; i++) {
				if (!isTrimNull(idArry[i])) {
					arrayList.add(idArry[i]);
				}
			}
		}
		return arrayList;
	}
	public static String listToString(List<String> list, char separator) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < list.size(); i++) {
			sb.append(list.get(i)).append(separator);
		}
		return sb.toString().substring(0, sb.toString().length() - 1);
	}
	public static String listToString2(List<Long> list, char separator) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < list.size(); i++) {
			sb.append(list.get(i)).append(separator);
		}
		return sb.toString().substring(0, sb.toString().length() - 1);
	}

	/**
	 * @author rc
	 * @data 2020-10-11
	 * 减掉最后一个字符
	 * @param str 
	 * @return 
	 * 
	 */
	public static String removeLastChar(String str) {
		if (StrUtils.isTrimNull(str) || str.length() < 2) return str;
		return str.substring(0, str.length()-2);
	}
	
	/**
	 * @author rc
	 * @data 2020-10-11
	 * 检查指定的字符串长度，如果小于给定长度，则在首位追加给定的字符
	 * @param code 指定字符串
	 * @param len 给定长度
	 * @param charachter 追加的字符
	 * @return
	 */
	public static String generateZeroCharacter(String code, int len, String charachter) {
	        StringBuilder str = new StringBuilder(code );
	        if (str.length() >= len) {
	            return str.toString();
	        }
	        int end = len - str.length();
	        for (int i = 0; i < end; i++) {
	            str.insert(0, charachter);
	        }
	        return str.toString();
  }
	/**
	 * @author rc
	 * @data 2020-10-11
	 * 检查指定的字符串长度，如果小于给定长度，则在尾部追加给定的字符
	 * @param code 指定字符串
	 * @param len 给定长度
	 * @param charachter 追加的字符
	 * @return
	 */
	public static String generateZeroCharacter2(String code, int len, String charachter) {
		StringBuilder str = new StringBuilder(code );
		if (str.length() >= len) {
			return str.toString();
		}
		int end = len - str.length();
		for (int i = 0; i < end; i++) {
			str.append(charachter);
		}
		return str.toString();
	}
	public static String getCode(String id, String prefixEnglish,Date currentDate) {
		StringBuilder sb = new StringBuilder(prefixEnglish);
			   sb.append(DateUtils.format(currentDate, DateUtils.DATE_TIME_FORMAT_NUMBER))
				.append(StrUtils.generateZeroCharacter(id, 6, "0")).append("0")
				.append(StrUtils.randomnum(999, 99999));
		return sb.toString();

	}
	public static String getCode( String prefixEnglish,Date currentDate) {
		StringBuilder sb = new StringBuilder(prefixEnglish);
		String code= DateUtils.format(currentDate, DateUtils.DATE_TIME_FORMAT_NUMBER).substring(9);
		sb.append(code)
		.append(StrUtils.randomnum(1, 9));
		return sb.toString();		
	}

	/**
	 * 获取随机的数字字符串
	 * @param length
	 * @return
	 */
	public static String getRandomNumberStr(int length) {
    	return RandomUtil.randomNumbers(length);
	}
   
    public static Date getExpireDate(){
    	// 订单过期时间默认3天
    			Long expiredDate = new Long((900  + System.currentTimeMillis() / 1000) * 1000);
    			return new Date( expiredDate);
    }



    
    public static String arrayToStr(List list, String separator) {    
    	return org.apache.commons.lang.StringUtils.join(list.toArray(),separator);    }

    /**
     * 驼峰转下划线
     * @param str   目标字符串
     * @return: java.lang.String
     */
    public static String humpToUnderline(String str) {
        String regex = "([A-Z])";
        Matcher matcher = Pattern.compile(regex).matcher(str);
        while (matcher.find()) {
            String target = matcher.group();
            str = str.replaceAll(target, "_"+target.toLowerCase());
        }
        return str;
    }

    /**
     * 下划线转驼峰
     * @param str   目标字符串
     * @return: java.lang.String
     */
    public static String underlineToHump(String str) {
        String regex = "_(.)";
        Matcher matcher = Pattern.compile(regex).matcher(str);
        while (matcher.find()) {
            String target = matcher.group(1);
            str = str.replaceAll("_"+target, target.toUpperCase());
        }
        return str;
    }


	
}

